package com.haifeng.asms.api.aop;

import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.http.HttpStatus;
import com.haifeng.asms.api.annotation.RedissionAnnotation;
import com.haifeng.asms.commons.exception.BusinessException;
import com.haifeng.asms.commons.utils.MessageUtil;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  分布式锁Aop
 * </p>
 *
 * @author: Haifeng
 * @date: 2020-06-21
 */
@Slf4j
@Aspect
@Component
@AllArgsConstructor
public class RedissionAop implements Ordered {

    private final RedissonClient redissonClient;
    private final MessageUtil messageUtil;

    @Pointcut("@annotation(com.haifeng.asms.api.annotation.RedissionAnnotation)")
    public void pointcut() {}

    @Around("pointcut()")
    public Object doConcurrentOperation(ProceedingJoinPoint pjp) throws Throwable {
        Signature signature = pjp.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        Method targetMethod = methodSignature.getMethod();
        RedissionAnnotation annotation = targetMethod.getAnnotation(RedissionAnnotation.class);
        String lockKey = annotation.lockKey();
        int retryTimes = annotation.retryTimes();
        Boolean getLock = false;
        RLock lock = null;
        try {
            while (retryTimes > 0) {
                log.info("尝试次数还剩{}次", retryTimes);
                retryTimes--;
                lock = redissonClient.getLock(lockKey);
                if (lock.isLocked()){
                    log.error("{}已被锁定", lockKey);
                    ThreadUtil.safeSleep(1000);
                    continue;
                }
                // 尝试加锁，最多等待2秒，上锁以后15秒自动解锁
                boolean tryLock = lock.tryLock(2, 15, TimeUnit.SECONDS);
                if (!tryLock){
                    log.error("{}加锁失败", lockKey);
                    ThreadUtil.safeSleep(1000);
                    continue;
                }
                getLock = true;
                break;
            }
            if (!getLock){
                log.error("{}分布式锁操作异常：获取锁并加锁操作失败", lockKey);
                throw new BusinessException(HttpStatus.HTTP_INTERNAL_ERROR, messageUtil.get(HttpStatus.HTTP_INTERNAL_ERROR));
            }
            // 业务处理
            log.info("{}获取锁成功，开始执行业务", lockKey);
            return pjp.proceed();
        }catch (Exception e){
            log.error("{}分布式锁操作异常：", lockKey, e.getMessage());
            throw new BusinessException(HttpStatus.HTTP_INTERNAL_ERROR,e.getMessage());
        }finally {
            try {
                lock.unlock();
            }catch (Exception e){
                log.error(e.getMessage());
            }
        }
    }

    @Override
    public int getOrder() {
        return Ordered.HIGHEST_PRECEDENCE;
    }
}
